package com.sangeng.service.impl;

import com.sangeng.entity.LoginUser;
import com.sangeng.entity.ResponseResult;
import com.sangeng.entity.User;
import com.sangeng.service.LoginService;
import com.sangeng.utils.JwtUtil;
import com.sangeng.utils.RedisCache;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginServiceImpl implements LoginService {


    @Resource
    private AuthenticationManager authenticationManager;

    @Resource
    private RedisCache redisCache;

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public ResponseResult login(User user) {
        // AuthenticationManager  authenticate  进行用户认证
        // 拿到用户输入的用户名和密码，封装成 authenticate 对象
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());

        // 用户验证
        Authentication authentication = null;
        try {
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername方法,做用户名验证
            authentication = authenticationManager
                    .authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                e.printStackTrace();
            } else {
                e.printStackTrace();
            }
        }


        // 认证通过，使用 userId 生成一个 jwt ，jwt 存入
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        // 使用用户ID生成 jwt，解析 jwt 结果为 用户 id
        String jwt = JwtUtil.createJWT(userId);

        Map<String, String> map = new HashMap<>(1);
        map.put("token", jwt);

        // 把完整用户信息存入 redis ，userId 作为 key
        redisCache.setCacheObject("login:" + userId, loginUser);

        // 返回结果
        return new ResponseResult(200, "登录成功", map);
    }

    /**
     * 退出登录
     *
     * @return
     */
    @Override
    public ResponseResult logout() {
        //获取当前登录用户的信息,从SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Long userid = loginUser.getUser().getId();

        //删除redis中的key
        redisCache.deleteObject("login:" + userid);
        return new ResponseResult(200, "注销成功");
    }

}
